package io.cw.service.impl.iml.reservation;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;


/**
 * 预约记录服务类
 *
 * @author cw
 */
@Service
@PropertySource("classpath:application-dev.yml")
public class EmailServiceImpl {

    // 发送端邮箱账户
    @Value("${mail.account}")
    public static String sendEmailAccount;

    @Value("${mail.authorization-code}")
    public static String sendAuthorizationCode;

    //发件人邮箱的 SMTP服务器地址
    @Value("${mail.host}")
    public static String myEmailSMTPHost;// qq


    public void sendEmali(String receiveEmail, String emailContext, String phone) throws Exception {
        //1.创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    //参数配置
        props.setProperty("mail.transport.protocol", "smtp");   //使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", myEmailSMTPHost);   //发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            //需要请求认证

        //2.根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getInstance(props);
        //设置为debug模式,可以查看详细的发送log
        session.setDebug(true);

        //3.创建一封邮件
        MimeMessage message = createMimeMessage(session, sendEmailAccount, receiveEmail, emailContext, phone);

        //4.根据 Session获取邮件传输对象
        Transport transport = session.getTransport();

        // 5.使用邮箱账号和密码连接邮件服务器, 这里认证的邮箱必须与 message中的发件人邮箱一致,否则报错
        transport.connect(sendEmailAccount, sendAuthorizationCode);
        //6.发送邮件,发到所有的收件地址,message.getAllRecipients()获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());
        System.out.println("邮件发送成功");
        // 7. 关闭连接
        transport.close();
    }


    /**
     * 创建文本邮件
     *
     * @param session 和服务器交互的会话
     * @param sendMail 发件人邮箱
     * @param receiveMail 收件人邮箱
     * @param content
     * @param phone
     * @return
     * @throws Exception
     */
    public MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String emailContext, String phone) throws Exception {
        // 1.创建一封邮件
        MimeMessage message = new MimeMessage(session);
        // 2.From:发件人
        message.setFrom(new InternetAddress(sendMail, "预约抢座", "UTF-8"));
        // 3.To:收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, phone, "UTF-8"));
        // 4.Subject: 邮件主题
        message.setSubject("预约抢座通知", "UTF-8");
        // 5.Content: 邮件正文
        message.setContent(emailContext, "text/html;charset=UTF-8");
        // 6.设置发件时间
        message.setSentDate(new Date());
        // 7.保存设置
        message.saveChanges();
        return message;
    }
}
